/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-06-23 14:04:42
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { message } from 'antd';
import { DescDesignReducer } from '../reducers/DescDesignReducer';
import { SET_SELECT_AT, SET_SELECT_FOND, SET_SELECT_LEVEL, SET_TRANSFER_LIST } from '../constants';
import { createDescDesign, editDescDesign, fetchFormByCoordinate } from '@/api/system';

const initialState = {
  // 当前选中的项目
  selectFond: {},
  selectAT: {},
  selectLevel: {}
};

const DescDesignContext = createContext();

const DescDesignContextProvider = (props) => {
  const [state, dispatch] = useReducer(DescDesignReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中的全宗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    /**
     * @description: 设置选中的层级
     */
    setSelectLevel(data) {
      dispatch({ type: SET_SELECT_LEVEL, data });
    },

    /**
     * @description: 获取移交清单列表
     */
    getDescForm(params) {
      return new Promise((resolve, reject) => {
        fetchFormByCoordinate(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_TRANSFER_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    addDescFormFunc(params) {
      return new Promise((resolve, reject) => {
        createDescDesign(params)
          .then((res) => {
            message.success('添加成功');
            const { data } = res;
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    editDescFormFunc(params) {
      return new Promise((resolve, reject) => {
        editDescDesign(params)
          .then((res) => {
            message.success('编辑成功');
            const { data } = res;
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    }
  };

  // watch listQuery来加载排序列表
  useEffect(() => {}, []);

  return (
    <DescDesignContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </DescDesignContext.Provider>
  );
};

export const useDescDesignContext = () => {
  return useContext(DescDesignContext);
};

export { DescDesignContext, DescDesignContextProvider };
